import { ref } from 'vue'
import { defineStore } from 'pinia'
import accessEnum from "@/access/AccessEnum";
import {UserControllerService} from "../../generated";
import AccessEnum from "@/access/AccessEnum";
import {useRouter} from "vue-router";

const router = useRouter()
export const useUserStore = defineStore('counter', () => {

  const loginUser = ref({
    userName: '',
    userRole: accessEnum.NOT_LOGIN
  })

  //设置登录的用户名
  const setLoginUser = (user: string) => {
    loginUser.value.userName = user
  }

  const getLoginUser = async ({commit, state}: any, payload: any) => {
    // 从远程请求获取哦用户登录信息
    const res = await UserControllerService.getLoginUserUsingGet();
    if (res.code === 0){
      loginUser.value.userRole = AccessEnum.USER
    }else {
      loginUser.value.userName = ''
      loginUser.value.userRole = AccessEnum.NOT_LOGIN
    }
  }
  // 当前登录的用户id
  const userId = ref('')
  // 设置当前用户id
  const setUserId = (id: any) => {
    userId.value = id
  }
  // 存储token
  const token = ref('')

  //设置token
  const setToken = (t: any) => {
    token.value = t
  }
  // 删除token
  const removeToken = () => {
    token.value = ''
  }
  // 用户退出
  const logout = () => {
    removeToken()
    setLoginUser('未登录')
    loginUser.value.userRole = AccessEnum.NOT_LOGIN
  }
  return { loginUser, setLoginUser, token, getLoginUser, setToken, removeToken, logout, userId, setUserId }
},{
  persist: true
})
